import React, { useEffect, useState } from 'react'
import HeadBack from "@/components/HeadBack"
import "@/assets/css/activityDetail.scss"
import { Popup } from 'antd-mobile'
import arrowImg from "@/assets/images/arrowImg.png"
import trainImg from "@/assets/images/trainImg.png"
import finishImg from "@/assets/images/finishImg.png"
import noFinishImg from "@/assets/images/noFinishImg.png"
import noJoinImg from "@/assets/images/noJoinImg.png"
import { useLocation } from 'react-router-dom'
import { getActivityDetail, getActivityEnroll, getTotalSportModels } from "@/utils/dataUtil"

import { PullToRefresh, Toast, Image } from 'antd-mobile'
import { timeDiff, compareToDate, compareTo, dateDiff, timeConvert } from "@/utils/dateUtil"
import Countdown from "@/components/Countdown";

const buildModelMethod = (models, modelItem) => {
    let buildModels = [];
    models.forEach((item) => {
        if (modelItem.includes(item.key)) {
            buildModels.push(item.name);
        }
        if (item.children) {
            buildModels = [...buildModels, ...buildModelMethod(item.children, modelItem)]
        }
    })
    return buildModels;
}



export default function ActivityDetail() {

    const location = useLocation();

    const [detailData, setDetailData] = useState({})

    //查看运动的模式
    const [visibleModel, setVisibleModel] = useState(false)

    //是否已经报名
    const [enroll, setEnroll] = useState(false);

    //所有的运动模式
    const [models, setModels] = useState([]);

    //点击查看更多运动模式
    const clickLookMoreModel = () => {
        setVisibleModel(true);
    }

    async function loadRefresh() {
        const res = await getActivityDetail(location.state.id);
        if (res.status === 1) {
            setDetailData(res.data);
            setEnroll(res.data.status !== "un_enroll");
        }
    }

    //活动详情获取数据
    useEffect(() => {
        loadRefresh();
    }, []);

    //点击报名按钮
    const clickEnrollBtn = () => {
        if (compareTo(detailData.startDate) === 1) {
            Toast.show({
                content: '活动暂未开始',
                maskClickable: false,
            });
            return;
        }
        getActivityEnroll(detailData.id).then(res => {
            //获取成功
            if (res.status === 1) {
                loadRefresh();
            }
            if (res.status === 0) {
                Toast.show({
                    content: '报名失败',
                    maskClickable: false,
                });
            }
        })
    }

    //获取所有的运动模式
    useEffect(() => {
        getTotalSportModels().then(res => {
            if (res.status === 0) {
                Toast.show({
                    content: res.msg,
                    maskClickable: false,
                });
                return;
            }
            setModels(res.data);
        })
    }, [])

    useEffect(() => {
        window.scrollTo(0, 0)
    }, [])

    return (
        <>
            <HeadBack background={"#FFFFFF"} backTit={detailData.name && detailData.name} isHome="back"></HeadBack>

            <div className='adContainer' style={{ background: detailData.color && detailData.color }}>

                <PullToRefresh onRefresh={loadRefresh}>

                    {/* banner */}
                    {
                        detailData.banner && <Image src={detailData.banner} width={"100%"} height={"7.5rem"} fit='cover' />
                    }


                    {/* 内容部分 */}
                    <div className='adContent'>


                        <div className={enroll === false ? 'adDetailBox' : ''}>
                            {/* 没报名的详情介绍 */}
                            <div className={enroll === true ? 'adInfoEnrollBox' : 'adInfoBox'}>
                                <div className='adTit'>{detailData.name && detailData.name}</div>
                                <div className='adTagBox'>
                                    <ul className='adTags'>
                                        {
                                            detailData.tags && detailData.tags.map((item, index) => (
                                                <li className='adTag' key={index}>{item}</li>
                                            ))
                                        }

                                    </ul>
                                    {
                                        JSON.stringify(detailData) !== "{}" && compareToDate(detailData.endDate) !== false && detailData.status !== "finish" && <div className='adTagCount'>{detailData.count && detailData.count}人已参与</div>
                                    }

                                    {
                                        enroll && (<div className='adFinishStatus'>
                                            {/* 已完成 */}
                                            {
                                                detailData.status === "finish" && <img className='adFinishStatusImg' src={finishImg} alt='' />
                                            }
                                            {
                                                compareToDate(detailData.endDate) === false && detailData.status === "un_enroll" && <img className='adFinishStatusImg' src={noJoinImg} alt='' />
                                            }
                                            {
                                                compareToDate(detailData.endDate) === false && detailData.status === "enroll" && <img className='adFinishStatusImg' src={noFinishImg} alt='' />
                                            }
                                        </div>)
                                    }


                                </div>
                                {/* 线 */}
                                {enroll === false && <div className='adLine'></div>}

                                {
                                    detailData.status && (detailData.status !== "un_enroll" || compareToDate(detailData.endDate) === false) && <div className='adProgressBox'>
                                        {/* 头部进度 */}
                                        <div className='adProgressCountBox'>
                                            <div className='adProgressLeft'>

                                                <span className='adProgressLeftTotal'>{
                                                    detailData.target && detailData.target
                                                }</span>
                                                <span className='adProgressLeftUnit'>
                                                    {detailData.targetType && (detailData.targetType === "minute" ? "分钟" : "Kcal")}
                                                </span>
                                            </div>
                                            <div className='adProgressRight'>
                                                还剩{detailData.targetType && (detailData.targetType === "minute" ? Math.max(0, (detailData.target - (detailData.time / 60).toFixed(0))) : Math.max((detailData.target - detailData.calorie), 0))}
                                                <span className='adProgressLeftUnit'>{detailData.targetType && (detailData.targetType === "minute" ? "分钟" : "Kcal")}</span>
                                            </div>
                                        </div>
                                        {/* 进度 */}
                                        <div className='adTrainProgressBox'>
                                            <div className='adTrainProgressBc'></div>
                                            <div className='adTrainProgress' style={{ width: detailData.targetType === "minute" ? (Math.min(((detailData.time / 60).toFixed(0) / detailData.target), 1) * 100 + "%") : (Math.min((detailData.calorie / detailData.target), 1) * 100 + "%") }}></div>
                                        </div>
                                        {/* 差今天 */}
                                        <div className='adTrainProgressTip'>
                                            <span className='adTrainProgressTipTit'>距离活动结束：</span>
                                            <Countdown count={dateDiff(detailData.startDate, detailData.endDate)}></Countdown>
                                        </div>
                                    </div>
                                }

                            </div>
                            {/* 活动介绍 */}
                            <div className={enroll === true ? 'adIntroEnrollBox' : 'adIntroBox'}>
                                {/* 时间 */}
                                <div className='adIntroTimeBox'>
                                    <div className='adIntroTimeTit'>活动时间</div>
                                    <div className='adIntroTime'>{detailData.startDate && detailData.startDate.replace(/-/g, ".")} - {detailData.endDate && detailData.endDate.replace(/-/g, ".")}</div>
                                </div>
                                {/* 目标 */}
                                <div className='adIntroTimeBox adIntroTargetBox'>
                                    <div className='adIntroTimeTit'>活动目标</div>
                                    {
                                        detailData.targetType && <div className='adIntroTime'>{timeDiff(detailData.startDate, detailData.endDate)}天/{detailData.target}{detailData.targetType === "minute" ? '分钟' : 'Kcal'}</div>
                                    }

                                </div>
                                {/* 运动模式 */}
                                <div className='adIntroTimeBox adIntroModelBox'>
                                    <div className='adIntroTimeTit'>运动模式</div>
                                    <div className='adIntroModel' onClick={clickLookMoreModel}>
                                        <p className='adIntroModelTxt'>
                                            {
                                                detailData.sportType && buildModelMethod(models, detailData.sportType).map((item, index) => (
                                                    <span key={item}>{item}{(index + 1) !== detailData.sportType.length && <span>、</span>}</span>

                                                ))
                                            }
                                        </p>
                                        <img src={arrowImg} className='adIntroModelArrow' alt='' />
                                    </div>
                                </div>
                                {/* 线 */}
                                <div className='adModelLineBox'><div className='adModelLine'></div></div>
                                {/* 提示 */}
                                <div className='adModelTip'>
                                    <p className='adModelTipIcon'>* </p>
                                    <p className='adModelTipTxt'>使用绑定的小米手环，选择该活动支持的运动模式开始运动 活动期间，数据将会自动累加计算</p>
                                </div>
                            </div>
                        </div>

                        {/* 富文本 */}
                        {
                            detailData.content !== null && detailData.content !== "<p><br></p>" && (<div className='adRichContent'>
                                <div
                                    dangerouslySetInnerHTML={{
                                        __html: detailData.content
                                    }}
                                >
                                </div>
                            </div>)
                        }


                        {/* 提示 */}
                        {
                            enroll === true && (<div className='adTrainImgBox'>
                                <img className='adTrainImg' src={trainImg} alt='' />
                            </div>)
                        }



                        {/* 报名按钮 */}
                        {
                            JSON.stringify(detailData) !== "{}" && enroll === false && compareTo(detailData.startDate) !== 1 && (<div className='adEnrollBtnBox' style={{ background: "transparent" }} onClick={clickEnrollBtn}>
                                <div className='adEnrollBtn'>去报名</div>
                            </div>)
                        }

                        {
                            JSON.stringify(detailData) !== "{}" && enroll === false && compareTo(detailData.startDate) === 1 && (<div className='adEnrollBtnBox' style={{ background: "transparent" }}>
                                <div className='adEnrollBtn' style={{ color: "rgba(255, 255, 255, 0.50)" }}>暂未开始，{timeConvert(detailData.startDate)}开始</div>
                            </div>)
                        }



                    </div>

                </PullToRefresh>


                {/* 运动模式的查看弹出层 */}
                <Popup
                    visible={visibleModel}
                    onMaskClick={() => {
                        setVisibleModel(false)
                    }}
                    bodyStyle={{
                        borderTopLeftRadius: '23px',
                        borderTopRightRadius: '23px',
                        height: '10.94rem',
                    }}
                >
                    {/* 开始开发 */}
                    <div className='adModelTit'>更多运动模式</div>
                    {/* 每一个模式 */}
                    <ul className='adModelUl'>
                        {
                            detailData.sportType && buildModelMethod(models, detailData.sportType).map((item, index) => (
                                <li className='adModelLi' key={item}>
                                    <p className='adModelLiTit'>{item}</p>
                                </li>
                            ))
                        }
                    </ul>
                    {/* 确定和取消按钮 */}
                    <div className='adModelBtnBox'>
                        <div className='adModelBtnCancel' onClick={() => setVisibleModel(false)}>取消</div>
                        <div className='adModelBtnFix' onClick={() => setVisibleModel(false)}>确定</div>
                    </div>
                </Popup>
            </div>
        </>
    )
}
